import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import { User } from '../users/entities/user.entity';
// 导入bcrypt用于密码加密
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  // 验证用户凭据
  async validateUser(email: string, password: string): Promise<any> {
    const user = await this.usersService.findByEmail(email);
    if (!user) {
      return null;
    }

    // 使用bcrypt比较密码（代替之前的明文比较）
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (isPasswordValid) {
      // 返回用户信息（不包含密码）
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  // 生成JWT令牌
  async login(user: any) {
    const payload = {
      sub: user.id,
      email: user.email,
      roles: user.roles || ['user'],
    };

    return {
      access_token: this.jwtService.sign(payload),
      expires_in: 60,
    };
  }

  // 根据用户ID验证用户（修复参数错误）
  async validateUserById(userId: number): Promise<User> {
    return this.usersService.findOne(userId);
  }

  // 密码加密（供用户注册时使用）
  async hashPassword(password: string): Promise<string> {
    // 生成盐值并加密密码
    const saltRounds = 10;
    return bcrypt.hash(password, saltRounds);
  }
}
